package com.jmb.api.common.utils;


import com.alibaba.fastjson2.JSONObject;
import com.jmb.api.common.exception.LeaseException;
import com.jmb.api.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ValidUtil {

    public static void checkName(String str, String message) {
        if (StringUtils.isBlank(str)){
            log.error("参数校验失败：{}",message);
            throw new LeaseException(ResultCodeEnum.WEB_API_NAME);
        }
    }
    public static void checkPage(Long page, Long pageSize) {
        if (page == null || page < 1) {
            log.error("参数校验失败：page");
            throw new LeaseException(ResultCodeEnum.WEB_API_PAGE);
        }
        if (pageSize == null || pageSize < 1) {
            log.error("参数校验失败：pageSize");
            throw new LeaseException(ResultCodeEnum.WEB_API_PAGE);
        }
    }
    public static void checkId(Integer id) {
        if (id == null || id < 0) {
            log.error("参数校验失败：id");
            throw new LeaseException(ResultCodeEnum.WEB_API_ID_NOT_NULL);
        }
    }
    public static void isJsonObject(String json) {
        if (StringUtils.isBlank(json)) {
            log.error("参数校验失败：json");
            throw new LeaseException(ResultCodeEnum.WEB_API_DATA_JSON_NULL);
        }
        try{
            JSONObject.parseObject(json);
        }catch (Exception e){
            log.error("参数校验失败：json");
            throw new LeaseException(ResultCodeEnum.WEB_API_DATA_JSON_ERROR);
        }
    }
    public static void isJsonPath(String jsonPath) {
        if (StringUtils.isBlank(jsonPath)){
            throw new LeaseException(ResultCodeEnum.WEB_API_DATA_JSON_PATH_NULL);
        }
        if (!jsonPath.startsWith("$")){
            throw new LeaseException(ResultCodeEnum.WEB_API_DATA_JSON_PATH_ERROR);
        }
    }
    public static void isXmlPath(String xmlPath){
        if (StringUtils.isBlank(xmlPath)){
            throw new LeaseException(ResultCodeEnum.WEB_API_DATA_XML_PATH_NULL);
        }
        if (!xmlPath.startsWith("//")){
            throw new LeaseException(ResultCodeEnum.WEB_API_DATA_XML_PATH_ERROR);
        }
    }
}
